import inspect

from django.contrib.contenttypes import generic
from django.db import models

from middleware.requestlocals import request_locals

invalid_fields = (
    models.fields.AutoField,
    generic.GenericRelation,
)


NULL_IP = '0.0.0.0'
NULL_USER = None
NULL_COMMENT = ''

def get_user_ip():
    try:
        request = request_locals.request
    except AttributeError:
        return NULL_USER, NULL_IP, NULL_COMMENT
    ip = request.META.get('REMOTE_ADDR', NULL_IP)
    comment = request.REQUEST.get('hst_comment', NULL_COMMENT)
    user = getattr(request, 'user', NULL_USER)
    return user, ip, comment


def chain_fields(instance):
    """ Yields all standard and many_to_many fields except `invalid_fields`
    """
    for f in instance._meta.fields:
        if not isinstance(f, invalid_fields) and not f.primary_key:
            yield f
    for f in instance._meta.many_to_many:
        if not isinstance(f, invalid_fields):
            yield f

def iter_original_fields(instance):
    for f in instance._meta.fields:
        if not f.primary_key and not f.name.startswith('hst_'):
            yield f

if __name__ == "__main__":
    """ run doctest """
    import doctest
    doctest.testmod()
